package com.bdqn.petmalldemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.petmalldemo.bo.PetAddBo;
import com.bdqn.petmalldemo.bo.ProductUpdateBo;
import com.bdqn.petmalldemo.bo.SearchProductBo;
import com.bdqn.petmalldemo.common.KetaiException;
import com.bdqn.petmalldemo.common.ResultCodeEnum;
import com.bdqn.petmalldemo.common.SystemConstants;
import com.bdqn.petmalldemo.common.TokenCache;
import com.bdqn.petmalldemo.entity.Category;
import com.bdqn.petmalldemo.entity.Product;
import com.bdqn.petmalldemo.entity.User;
import com.bdqn.petmalldemo.mapper.CategoryMapper;
import com.bdqn.petmalldemo.mapper.ProductMapper;
import com.bdqn.petmalldemo.mapper.UserMapper;
import com.bdqn.petmalldemo.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lenovo
 * @since 2020-02-10
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Override
    public Map<String,Object> searchProduct(SearchProductBo searchProductBo) {
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper
                .orderByDesc("create_time")
                //商品名称模糊查询
                .like(!StringUtils.isEmpty(searchProductBo.getProductName()),
                        "name",searchProductBo.getProductName())
                //用户Id 动态条件
                .eq(!StringUtils.isEmpty(searchProductBo.getUserId()),"user_id",searchProductBo.getUserId());
        if (!StringUtils.isEmpty(searchProductBo.getCategoryIds())&&!searchProductBo.getCategoryIds().equals("0")) {
            //当商品分类Id不能为空
            //讲String类型的参数转化成为Integer类型
            String[] category = searchProductBo.getCategoryIds().split(",");
            //绑定到queryWrapper对象
            productQueryWrapper.in("category_id",category);
        }
        if (!StringUtils.isEmpty(searchProductBo.getStatusList())&& searchProductBo.getStatusList().contains(",")) {
            String[] status = searchProductBo.getStatusList().split(",");
            productQueryWrapper.in("status",status);
        }
        Map<String,Object> map=new HashMap<>(16);
        IPage<Product> page=new Page<>(searchProductBo.getCurrentPage(),searchProductBo.getPageSize());
            baseMapper.selectPage(page,productQueryWrapper);
            map.put("list",page.getRecords());
            map.put("pageNum",page.getCurrent());
            //判断类型是否为空
        if (StringUtils.isEmpty(searchProductBo.getStatusList())) {
            map.put("pages",page.getPages());
            map.put("total",page.getTotal());
        }

        return map;
    }

    @Override
    public List<Product> hotTopProduct() {
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        IPage<Product> page=new Page<>(1,10);
        productQueryWrapper.orderByAsc("view_num")
                .eq("status",6);
        baseMapper.selectPage(page,productQueryWrapper);
        return page.getRecords();
    }

    @Override
    public List<Product> recommendProduct() {
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("recommend",1)
                .eq("status",6);
        return baseMapper.selectList(productQueryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPet(PetAddBo petAddBo) {
        User user = JSONObject.parseObject(TokenCache.get(petAddBo.getToken()), User.class);
        Product product = new Product();
        BeanUtils.copyProperties(petAddBo,product);
        product.setUserId(user.getId())
                .setUserName(user.getUsername());
        //处理主图和商品子图
        product.setMainImage(petAddBo.getSubImage().split(",")[0]);
        baseMapper.insert(product);
        //更新相关联的用户相关数据,宠物数量，在售宠物数量
        //1.先获取关联用户信息
        User userById = userMapper.selectById(user.getId());
        //2.更新宠物数量
        userById.setPetNum(userById.getPetNum()+1);
        //3.将更新的用户数据写回数据库
        userMapper.updateById(userById);
    }

    @Override
    public void updateProduct(ProductUpdateBo productUpdateBo) {
        //先根据Id查出商品信息
        Product product = this.getById(productUpdateBo.getId());
        //TODD:2020/3/2 判断商品是否存在
       if (product==null) {
            throw new KetaiException(ResultCodeEnum.PRODUCT_NULL);
        }
        BeanUtils.copyProperties(productUpdateBo,product);
        //处理主图和商品子图
        product.setMainImage(productUpdateBo.getSubImage().split(",")[0]);
        baseMapper.updateById(product);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteProductById(String id) {
        //先要减少相关用户的宠物数量
        User user = userMapper.selectById(this.getById(id).getUserId());
        user.setPetNum(user.getPetNum()-1);
        userMapper.updateById(user);
        //删除当前商品
        baseMapper.deleteById(id);
    }

    @Override
    public void updateProductStatus(String productId,Integer status) {
        //根据id修改状态
        Product productById = baseMapper.selectById(productId);
        //根据状态做不同的调整
        productById.setStatus(status);
        //1.判断当前的商品状态,如果当前商品状态大于将要修改的状态,返回错误信息
        if (productById.getStatus()>status) {
            throw  new  KetaiException(ResultCodeEnum.FAILED);
        }
      //2.如果当前需要调整的状态上架，就需要同步调整当前用户的在售宠物数量
        if (status.equals(SystemConstants.PRODUCT_STATUS.SHELVES)) {
            //修改当前用户的在售宠物数量
            User user = userMapper.selectById(productById.getUserId());
            user.setOnsalePetNum(user.getOnsalePetNum()+1);
            userMapper.updateById(user);
        }
        baseMapper.updateById(productById);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addViewNum(String productId, Long categoryId){
        //根据商品Id查询商品信息
        Product productbyId = baseMapper.selectById(productId);
        //取出浏览记录数+1
        long newViewNum=productbyId.getViewNum()+1;
        productbyId.setViewNum(newViewNum);
        baseMapper.updateById(productbyId);

        //更新商品分类的浏览记录数
        Category category = categoryMapper.selectById(categoryId);
        category.setViewNum(category.getViewNum()+1);
        categoryMapper.updateById(category);

    }
}

